<?php

declare(strict_types=1);

namespace App\Listener;

use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Validator;

#[Listener]
class ValidatorResolvedListener implements ListenerInterface
{

    protected ValidatorFactoryInterface $validatorFactory;

    public function listen(): array
    {
        return [
            \Hyperf\Validation\Event\ValidatorFactoryResolved::class,
        ];
    }

    public function process(object $event): void
    {
        $validatorFactory = $event->validatorFactory;
        // 注册了 foo 验证器
        $validatorFactory->extend('chinese', function (string $attribute, mixed $value, array $parameters, Validator $validator): bool {
            $chineseRegex = '[\x{4e00}-\x{9fa5}]';
            $paramCount = count($parameters);
            if ($paramCount == 1 && is_numeric($parameters[0])) {
                $regex = "/^$chineseRegex{{$parameters[0]},}$/u";
            } elseif ($paramCount >= 2 && is_numeric($parameters[0]) && is_numeric($parameters[1])) {
                $regex = "/^$chineseRegex{{$parameters[0]},{$parameters[1]}}$/u";
            } else {
                $regex = "/^$chineseRegex+$/u";
            }
            return (bool)preg_match($regex, $value);
        });
        // 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符这里扩展了 :foo 占位符
        $validatorFactory->replacer('chinese', function (string $message, string $attribute, string $rule, array $parameters): array|string {
            $message = $attribute . ' 必须由中文组成';
            $paramCount = count($parameters);
            if ($paramCount == 1 && is_numeric($parameters[0])) {
                $message .= "，且不少于 {$parameters[0]} 个字符";
            } elseif ($paramCount >= 2 && is_numeric($parameters[0]) && is_numeric($parameters[1])) {
                $message .= "，且字符串长度在 {$parameters[0]} 到 {$parameters[1]} 之间";
            }
            return $message;
        });
    }

}